import datetime

from other.cfg import Config
from other.change_format import change_format
from other.status import Status
from server.Mysql import MySQL
from other.sql_montage import sqlMontage


class Menu:
    def __init__(self):
        self.cfg = Config()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'sys_menu')
        self.st = Status()
        self.cf = change_format()
        self.sm = sqlMontage()

    def get_menu(self, user_id):
        result = {'msg': '成功', 'code': 200, 'data': []}
        ur_sql = f"select sur.*,sr.`role_key` from `sys_user_role` sur join `sys_role` sr on sr.`role_id`=sur.`role_id` where sur.`user_id`={user_id}"
        ur_res = self.db.gets(ur_sql)
        # print('ur_res', ur_res)
        if ur_res != ():
            # 获取所有子集
            for ur in ur_res:
                # 子集
                children = []
                if ur['role_key'] != 'admin':
                    me_sql = f"SELECT DISTINCT sm.* FROM `sys_menu` sm JOIN `sys_role_menu` srm ON sm.`menu_id` = srm.`menu_id` WHERE srm.`role_id` = {ur['role_id']}"
                else:
                    res = self.get_menu_all()
                    result['data'] = res['data']
                    return result
                me_res = self.db.gets(me_sql)
                # print('me_res', me_res)
                if me_res != ():
                    for me in me_res:
                        pi = {}
                        cc_meta = {}
                        for key, value in me.items():
                            if isinstance(value, datetime.datetime):
                                me[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                        name = me['path'].title()
                        me['name'] = name
                        cc_meta['title'] = me['menu_name']
                        cc_meta['icon'] = me['icon']
                        me['meta'] = cc_meta
                        pi[me['parent_id']] = me
                        children.append(pi)
            # print('children', children)
            # 拼接父级id
            pps = {}
            for item in children:
                for p_key, p_value in item.items():
                    if p_key not in pps:
                        pps[p_key] = []
                    pps[p_key].append(p_value)
            # print('pps', pps)
            for pp_key, pp_value in pps.items():
                p_sql = f"where `menu_id`={pp_key}"
                p_res = self.db.get(p_sql)
                # print('p_res', p_res)
                if p_res != ():
                    for p in p_res:
                        meta = {}
                        for key, value in p.items():
                            if isinstance(value, datetime.datetime):
                                p[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                        name = p['path'].title()
                        p['name'] = name
                        p['path'] = "/" + p['path']
                        p['redirect'] = 'noRedirect'
                        p['component'] = 'Layout'
                        meta['title'] = p['menu_name']
                        meta['icon'] = p['icon']
                        p['meta'] = meta
                        p['children'] = pp_value
                        result['data'].append(p)
        # print('result', result)
        result = self.cf.changes_format(result)
        return result

    # 获取所有菜单
    def get_menu_all(self):
        result = {'msg': '成功', 'code': 200, 'data': []}
        p_sql = "where `parent_id`=0 ORDER BY `order_num` ASC"
        p_res = self.db.get(p_sql)
        if p_res != ():
            for pp in p_res:
                meta = {}
                for key, value in pp.items():
                    if isinstance(value, datetime.datetime):
                        pp[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                name = pp['path'].title()
                pp['name'] = name
                pp['path'] = pp['path']
                pp['redirect'] = 'noRedirect'
                pp['component'] = 'Layout'
                meta['title'] = pp['menu_name']
                meta['icon'] = pp['icon']
                pp['meta'] = meta
                pp['children'] = []
                c_sql = f"where `parent_id`={pp['menu_id']} ORDER BY `order_num` ASC"
                c_res = self.db.get(c_sql)
                if c_res != ():
                    for cc in c_res:
                        cc_meta = {}
                        for key, value in cc.items():
                            if isinstance(value, datetime.datetime):
                                cc[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                        name = cc['path'].title()
                        cc['name'] = name
                        cc_meta['title'] = cc['menu_name']
                        cc_meta['icon'] = cc['icon']
                        cc['meta'] = cc_meta
                        pp['children'].append(cc)
                result['data'].append(pp)
        result = self.cf.changes_format(result)
        return result

    # 新增菜单
    def menu_add(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        n_sql = f"where `menu_name`='{data['menuName']}'"
        n_res = self.db.get(n_sql)
        if n_res == ():
            # add_sql = "(`menu_name`,`parent_id`,`order_num`,`path`,`component`,`menu_type`,`visible`,`perms`,`icon`,`create_by`,`create_time`) values ('{}',{},{},'{}','{}','{}','{}','{}','{}','{}','{}')".format(
            #     data['menuName'], data['parentId'], data['orderNum'], data['path'], component, data['menuType'],
            #     data['visible'], perms, icon, userInfo['userName'], times)
            # add_sql = add_sql.replace("'None'", "NULL").replace("None", "NULL")
            # self.db.add(add_sql)
            data['create_by'] = userInfo['userName']
            data['create_time'] = times
            add_sql = self.sm.add_sql_data(data, 'sys_menu')
            # print('add_sql', add_sql)
            self.db.adds(add_sql, 'sys_menu')
        else:
            result['code'] = 500
            result['msg'] = '菜单名称已存在'
        return result

    # 修改菜单
    def menu_edit(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        n_sql = f"where `menu_name`='{data['menuName']}'"
        n_res = self.db.get(n_sql)
        # print('n_res', n_res)
        ff = False
        if n_res != ():
            for n in n_res:
                if n['menu_id'] == data['menuId']:
                    ff = True
                else:
                    ff = False
                    result['code'] = 500
                    result['msg'] = '菜单名称已存在'
                    break
        else:
            ff = True
        if ff:
            # if data.get('perms') is None:
            #     perms = None
            # else:
            #     perms = data['perms']
            # if data.get('component') is None:
            #     component = None
            # else:
            #     component = data['component']
            # edit_sql = "`menu_name`='{}',`parent_id`={},`order_num`={},`path`='{}',`component`='{}',`menu_type`='{}',`visible`='{}',`perms`='{}',`icon`='{}',`update_by`='{}',`update_time`='{}' where `menu_id`={}".format(
            #     data['menuName'], data['parentId'], data['orderNum'], data['path'], component, data['menuType'],
            #     data['visible'], perms, data['icon'], userInfo['userName'], times, data['menuId'])
            # self.db.edit(edit_sql)
            if 'createTime' in data:
                del data['createTime']
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'sys_menu', 'menu_id', data['menuId'])
            # print('edit_sql', edit_sql)
            self.db.edits(edit_sql, 'sys_menu')
        return result

    # 删除菜单
    def menu_del(self, data):
        result = {'msg': '成功', 'code': 200}
        ids = [int(x) for x in data.split(',')]
        for i in ids:
            n_sql = f"where `menu_id`={i}"
            self.db.delete(n_sql)
        return result
